package cn.net.wangyixinwen.mvvm.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import cn.net.wangyixinwen.databinding.FragmentHomeBinding;
import cn.net.wangyixinwen.mvvm.activity.NewsDetailsActivity;
import cn.net.wangyixinwen.mvvm.adapter.HomeAdapter;
import cn.net.wangyixinwen.mvvm.vm.HomeVM;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding viewBinding;

    private HomeVM homeVM = new HomeVM();

    private HomeAdapter homeAdapter = new HomeAdapter();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = FragmentHomeBinding.inflate(LayoutInflater.from(requireContext()));
        return viewBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initObserver();
        LinearLayoutManager lm = new LinearLayoutManager(requireContext());
        viewBinding.rvList.setAdapter(homeAdapter);
        viewBinding.rvList.setLayoutManager(lm);

        homeVM.getHomeData();

        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(requireContext(), NewsDetailsActivity.class);
                intent.putExtra("data", homeAdapter.getItem(position));
                startActivity(intent);
            }
        });
    }

    public void initObserver() {
        homeVM.eventList.observe(this, list -> homeAdapter.setNewData(list));
    }

}

